package com.muyangren.poidemo.one;

import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.config.ConfigureBuilder;
import com.deepoove.poi.data.*;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;

@RestController
public class TestController {


    public static void main(String[] args) throws IOException, InvalidFormatException {
        // 获取模板文件流
        ClassPathResource classPathResource = new ClassPathResource("templates" + File.separator + "sample.docx");
        InputStream inputStream = classPathResource.getInputStream();
        //poi-tl 配置
        ConfigureBuilder builder = Configure.builder();
        builder.useSpringEL(false);

        Map<String,Object> map = new HashMap<>();

        PictureRenderData pictureRenderData = Pictures.ofStream(new FileInputStream("B:\\workspace3\\poi-demo\\src\\main\\resources\\pictures\\1678518551044.png"), PictureType.PNG)
                .size(126, 126).create();
        map.put("picture",pictureRenderData);

        //联系人
        ContactInformation contactInformation = initContactInformation();
        map.put("contact",contactInformation);
        // 伪造一个表格数据
        //单个表格
        VectorTableData vector = getVectorTableData();
        map.put("vector", vector);
        builder.bind("vector",new VectorTablePolicy());

        PlamidTableData plasmid = getPlasmidTableData();
        map.put("plasmid", plasmid);
        builder.bind("plasmid",new PlasmidTablePolicy());

        VirusTableData  virus = getVirusTableData();
        map.put("virus",virus);
        builder.bind("virus",new VirusTablePolicy());

        CheckTableData check = getCheckTableData();
        map.put("check",check);
        builder.bind("check",new CheckTablePolicy());

        XWPFTemplate template = XWPFTemplate.compile(inputStream, builder.build()).render(map);

//        XWPFDocument document = template.getXWPFDocument();
//        for (XWPFParagraph itemParagraph : document.getParagraphs()) {
//            for (XWPFRun itemRun : itemParagraph.getRuns()) {
//
////                for (XWPFPicture itemEmbeddedPicture : itemRun.getEmbeddedPictures()) {
////                    // 确定某个图片（这里的图片之所以有自定义的描述，是因为图片是通过代码插入的）
////                    if (StringUtils.equals("xxx.jpg", itemEmbeddedPicture.getDescription())) {
////                        // 待替换的图片文件
////                        File toReplaceImage = new File("xxx.jpg");
////                        try (InputStream toReplaceImageInputStream = Files.newInputStream(toReplaceImage.toPath())) {
////                            // 替换图片
////                            itemEmbeddedPicture.getCTPicture().getBlipFill().getBlip().setEmbed(document.addPictureData(
////                                    toReplaceImageInputStream,
////                                    XWPFDocument.PICTURE_TYPE_JPEG));
////                            // 根据图片修改大小
////                            BufferedImage bufferedImage = ImageIO.read(toReplaceImage);
////                            itemRun.getCTR().getDrawingArray(0).getInlineList().get(0).getExtent().setCx(5000000L);
////                            itemRun.getCTR().getDrawingArray(0).getInlineList().get(0).getExtent().setCy(5000000L * bufferedImage.getHeight() / bufferedImage.getWidth());
////                            itemEmbeddedPicture.getCTPicture().getSpPr().getXfrm().getExt().setCx(5000000L);
////                            itemEmbeddedPicture.getCTPicture().getSpPr().getXfrm().getExt().setCy(5000000L * bufferedImage.getHeight() / bufferedImage.getWidth());
////                        }
////                    }
////                }
//            }
//        }


//        replaceImage(document, "image_placeholder", "B:\\workspace3\\poi-demo\\src\\main\\resources\\pictures\\1678518551044.png");

        template.writeAndClose(
                Files.newOutputStream(
                        Paths.get("B:\\workspace3\\poi-demo\\src\\main\\resources\\templates\\"+ UUID.randomUUID()+".docx")));

    }

    /**
     * 使用Apache POI替换Word文档中的图片
     * @param document 文档对象
     * @param placeholder 图片占位符文本
     * @param imagePath 新图片路径
     */
    public static void replaceImage(XWPFDocument document, String placeholder, String imagePath) throws IOException, InvalidFormatException {
        List<XWPFParagraph> paragraphs = document.getParagraphs();
        for (XWPFParagraph paragraph : paragraphs) {
            List<XWPFRun> runs = paragraph.getRuns();
            for (XWPFRun run : runs) {
                String text = run.getText(0);
                if (text != null && text.contains(placeholder)) {
                    int idx = text.indexOf(placeholder);
                    if (idx >= 0) {
                        // 移除旧图片
                        for (int i = 0; i <= idx; i++) {
                            run.setText("", i);
                        }

                        FileInputStream fileInputStream = new FileInputStream(imagePath);
                        // 插入新图片
//                        byte[] imageData = BytePictureUtils.getBytes(new FileInputStream(imagePath));
//                        int width = 200; // 图片宽度
//                        int height = 200; // 图片高度
                        run.addPicture(fileInputStream, XWPFDocument.PICTURE_TYPE_JPEG, "image.jpg",200, 200);
                    }
                }
            }
        }
    }

    /*
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws IOException {
        // 获取模板文件流
        InputStream resourceAsStream =
                this.getClass().getResourceAsStream("/word/template.docx");
        //poi-tl 配置
        ConfigureBuilder builder = Configure.builder();
        builder.useSpringEL(false);

        Map<String,Object> map = new HashMap<>();

        // 伪造一个表格数据
        //单个表格
        ServerTableData oneTable = getServerTableData();
        map.put("oneTable",oneTable);
        builder.bind("oneTable",new ServerTablePolicy());

        //多个表格
        List<Map<String, Object>> dynamicFlag = new ArrayList<>();
        // 伪造3个表格数据
        for (int i = 0; i < 3; i++) {
            ServerTableData tableData = getServerTableData();
            Map<String, Object> dynamicTableMap = new HashMap<>();
            dynamicTableMap.put("serverListTable", tableData);
            dynamicTableMap.put("tableName", "表名");
            dynamicFlag.add(dynamicTableMap);
        }
        map.put("listTable",dynamicFlag);
        builder.bind("serverListTable",new ServerTablePolicy());

        XWPFTemplate template = XWPFTemplate.compile(Objects.requireNonNull(resourceAsStream), builder.build()).render(map);
        //输出网络流
        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition","attachment;filename=\""+"out_template.docx"+"\"");
        // HttpServletResponse response
        OutputStream out = response.getOutputStream();
        BufferedOutputStream bos = new BufferedOutputStream(out);
        template.write(bos);
        bos.flush();
        out.flush();
        PoitlIOUtils.closeQuietlyMulti(template, bos, out);
    }*/

    public static VectorTableData getVectorTableData() {
        List<VectorInformation> vectorInformations = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            VectorInformation vectorInformation = new VectorInformation();
            vectorInformation.setAmount("amount"+i);
            vectorInformation.setRemark("remark"+i);
            vectorInformation.setOrderNo("order"+i);
            vectorInformation.setTemplateType("type"+i);
            vectorInformation.setTemplateName("name"+i);
            vectorInformations.add(vectorInformation);
        }

        List<RowRenderData> vectorInformationList = new ArrayList<>();
        for (VectorInformation vectorInformation : vectorInformations) {
            List<CellRenderData> cellDataList = new ArrayList<>();
            cellDataList.add(new CellRenderData().addParagraph(new ParagraphRenderData().addText(vectorInformation.getOrderNo())));
            cellDataList.add(new CellRenderData().addParagraph(new ParagraphRenderData().addText(vectorInformation.getTemplateName())));
            cellDataList.add(new CellRenderData().addParagraph(new ParagraphRenderData().addText(vectorInformation.getTemplateType())));
            cellDataList.add(new CellRenderData().addParagraph(new ParagraphRenderData().addText(vectorInformation.getAmount())));
            cellDataList.add(new CellRenderData().addParagraph(new ParagraphRenderData().addText(vectorInformation.getRemark())));
            RowRenderData rowRenderData = new RowRenderData();
            // 样式
            rowRenderData.setCells(cellDataList);
            vectorInformationList.add(rowRenderData);
        }
        VectorTableData serverTableData = new VectorTableData();
        serverTableData.setServerDataList(vectorInformationList);
        return serverTableData;
    }

    public static PlamidTableData getPlasmidTableData() {
        List<PlasmidInformation> plasmidInformations = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            PlasmidInformation plasmidInformation = new PlasmidInformation();
            plasmidInformation.setOrderNo("order"+i);
            plasmidInformation.setPlasmidName("plasmid"+i);
            plasmidInformation.setResistance("resistance"+i);
            plasmidInformation.setSendType("sendType"+i);
            plasmidInformation.setAmount("amount"+i);
            plasmidInformation.setRemark("remark"+i);
            plasmidInformations.add(plasmidInformation);
        }

        List<RowRenderData> plasmidInformationList = new ArrayList<>();
        for (PlasmidInformation plasmidInformation : plasmidInformations) {
            List<CellRenderData> cellDataList = new ArrayList<>();
            cellDataList.add(new CellRenderData().addParagraph(new ParagraphRenderData().addText(plasmidInformation.getOrderNo())));
            cellDataList.add(new CellRenderData().addParagraph(new ParagraphRenderData().addText(plasmidInformation.getPlasmidName())));
            cellDataList.add(new CellRenderData().addParagraph(new ParagraphRenderData().addText(plasmidInformation.getResistance())));

            cellDataList.add(new CellRenderData().addParagraph(new ParagraphRenderData().addText(plasmidInformation.getAmount())));
            cellDataList.add(new CellRenderData().addParagraph(new ParagraphRenderData().addText(plasmidInformation.getSendType())));
            cellDataList.add(new CellRenderData().addParagraph(new ParagraphRenderData().addText(plasmidInformation.getTubeName())));

            cellDataList.add(new CellRenderData().addParagraph(new ParagraphRenderData().addText(plasmidInformation.getRemark())));
            RowRenderData rowRenderData = new RowRenderData();
            // 样式
            rowRenderData.setCells(cellDataList);
            plasmidInformationList.add(rowRenderData);
        }
        PlamidTableData serverTableData = new PlamidTableData();
        serverTableData.setServerDataList(plasmidInformationList);
        return serverTableData;
    }

    public static VirusTableData getVirusTableData() {
        List<VirusInformation> virusInformations = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            VirusInformation virusInformation = new VirusInformation();
            virusInformation.setOrderNo("order"+i);
            virusInformation.setVirusName("virus"+i);
            virusInformation.setResistance("resistance"+i);
            virusInformation.setTrLength("trLength"+i);
            virusInformation.setMorphology("morphology"+i);
            virusInformation.setGene("gene"+i);
            virusInformation.setOriginal("original"+i);
            virusInformation.setTubeName("tubeName"+i);
            virusInformation.setRemark("remark"+i);
            virusInformations.add(virusInformation);
        }

        List<RowRenderData> virusInformationList = new ArrayList<>();
        for (VirusInformation virusInformation : virusInformations) {
            List<CellRenderData> cellDataList = new ArrayList<>();
            cellDataList.add(new CellRenderData().addParagraph(new ParagraphRenderData().addText(virusInformation.getOrderNo())));
            cellDataList.add(new CellRenderData().addParagraph(new ParagraphRenderData().addText(virusInformation.getVirusName())));
            cellDataList.add(new CellRenderData().addParagraph(new ParagraphRenderData().addText(virusInformation.getResistance())));
            cellDataList.add(new CellRenderData().addParagraph(new ParagraphRenderData().addText(virusInformation.getTrLength())));
            cellDataList.add(new CellRenderData().addParagraph(new ParagraphRenderData().addText(virusInformation.getMorphology())));
            cellDataList.add(new CellRenderData().addParagraph(new ParagraphRenderData().addText(virusInformation.getGene())));
            cellDataList.add(new CellRenderData().addParagraph(new ParagraphRenderData().addText(virusInformation.getOriginal())));
            cellDataList.add(new CellRenderData().addParagraph(new ParagraphRenderData().addText(virusInformation.getTubeName())));
            cellDataList.add(new CellRenderData().addParagraph(new ParagraphRenderData().addText(virusInformation.getRemark())));
            RowRenderData rowRenderData = new RowRenderData();
            // 样式
            rowRenderData.setCells(cellDataList);
            virusInformationList.add(rowRenderData);
        }
        VirusTableData serverTableData = new VirusTableData();
        serverTableData.setServerDataList(virusInformationList);
        return serverTableData;
    }

    public static CheckTableData getCheckTableData() {
        List<CheckInformation> checkInformations = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            CheckInformation checkInformation = new CheckInformation();
            checkInformation.setOrderNo("order"+i);
            checkInformation.setCheckName("checkName"+i);
            checkInformation.setSpecification("specification"+i);
            checkInformation.setAmount("amount"+i);
            checkInformation.setType("type"+i);
            checkInformation.setCondition("condition"+i);
            checkInformation.setMeasure("measure"+i);
            checkInformation.setReclaim("reclaim"+i);
            checkInformation.setRemark("remark"+i);
            checkInformations.add(checkInformation);
        }

        List<RowRenderData> checkInformationList = new ArrayList<>();
        for (CheckInformation checkInformation : checkInformations) {
            List<CellRenderData> cellDataList = new ArrayList<>();
            cellDataList.add(new CellRenderData().addParagraph(new ParagraphRenderData().addText(checkInformation.getOrderNo())));
            cellDataList.add(new CellRenderData().addParagraph(new ParagraphRenderData().addText(checkInformation.getCheckName())));
            cellDataList.add(new CellRenderData().addParagraph(new ParagraphRenderData().addText(checkInformation.getSpecification())));
            cellDataList.add(new CellRenderData().addParagraph(new ParagraphRenderData().addText(checkInformation.getAmount())));
            cellDataList.add(new CellRenderData().addParagraph(new ParagraphRenderData().addText(checkInformation.getType())));
            cellDataList.add(new CellRenderData().addParagraph(new ParagraphRenderData().addText(checkInformation.getCondition())));
            cellDataList.add(new CellRenderData().addParagraph(new ParagraphRenderData().addText(checkInformation.getMeasure())));
            cellDataList.add(new CellRenderData().addParagraph(new ParagraphRenderData().addText(checkInformation.getReclaim())));
            cellDataList.add(new CellRenderData().addParagraph(new ParagraphRenderData().addText(checkInformation.getRemark())));
            RowRenderData rowRenderData = new RowRenderData();
            // 样式
            rowRenderData.setCells(cellDataList);
            checkInformationList.add(rowRenderData);
        }
        CheckTableData serverTableData = new CheckTableData();
        serverTableData.setServerDataList(checkInformationList);
        return serverTableData;
    }

    public static ContactInformation initContactInformation() {
        // 填充一些基本信息
        ContactInformation templates = new ContactInformation();
        templates.setContractNumber("12313");
        templates.setContactEmail("牧羊人OVO");
        templates.setContactName("牧羊人OVo");
        templates.setContactPhone("青龙小组");
        templates.setCompanyName("未知");

        return templates;
    }
}
